package com.ylkj.patientdrug.adapter;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.examination.mlib.constants.ClickApi;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.UIUtils;
import com.ylkj.patientdrug.entity.DrugEntity;
import com.ylkj.patientdrug.entity.DrugPackEntity;
import com.ylkj.patientdrug.entity.MessageEvent;
import com.ylkj.patientdrug.R;
import com.ylkj.patientdrug.entity.O2oCartVOSEntity;
import com.ylkj.patientdrug.entity.ViewEntity;
import com.ylkj.patientdrug.ui.fragment.DruglistFragment;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.examination.mlib.constants.AllStringConstants.ITEM_TYPE_O2O_CART_VOS_COMMODITY;

public class DrugInfoAdapter extends BaseQuickAdapter<DrugEntity.CommodityListBean, BaseViewHolder> {


    private SpecAdapter specAdapter;
    private OnDeleteClickLister mDeleteClickListener;
    private List<String> list = new ArrayList<>();
    private int position;
    private int mItemType;
    private DrugEntity drugEntity;

    public DrugInfoAdapter(int layoutResId, @Nullable List<DrugEntity.CommodityListBean> data, int mItemType, DrugEntity drugEntity) {
        super(layoutResId, data);
        this.mItemType = mItemType;
        this.drugEntity = drugEntity;
    }

    @Override
    protected void convert(BaseViewHolder viewHolder, DrugEntity.CommodityListBean item) {
        ImageView drugImg = viewHolder.getView(R.id.drug_img);
        Glide.with(mContext).load(item.getImageUrl()).transform(new CenterCrop()).into(drugImg);

        if (mItemType == ITEM_TYPE_O2O_CART_VOS_COMMODITY) {
            //o2o
//            if (item.isSoldOut() || TextUtils.isEmpty(item.getInventoryQuantity())) {
//                viewHolder.setVisible(R.id.tv_sold_out, true);
//            } else {
//                viewHolder.setVisible(R.id.tv_sold_out, false);
//            }

            O2oCartVOSEntity entity = (O2oCartVOSEntity) drugEntity;
            if (entity.getDeliveryScope() == 2) {
                viewHolder.setVisible(R.id.tv_drug_status, true);
                viewHolder.setText(R.id.tv_drug_status, "超出配送范围");
                viewHolder.setVisible(R.id.tv_sold_out, false);
            } else if (entity.getBusinessScope() == 2) {
                viewHolder.setVisible(R.id.tv_drug_status, true);
                viewHolder.setText(R.id.tv_drug_status, "店铺休息");
                viewHolder.setVisible(R.id.tv_sold_out, false);
            } else {
                if (item.isSoldOut() || TextUtils.isEmpty(item.getInventoryQuantity())) {
                    viewHolder.setVisible(R.id.tv_sold_out, true);
                    viewHolder.setVisible(R.id.tv_drug_status, false);
                    viewHolder.setText(R.id.tv_drug_status, "");
                } else {
                    viewHolder.setVisible(R.id.tv_sold_out, false);
                    if (Integer.parseInt(item.getAddedQuantity()) > Integer.parseInt(item.getInventoryQuantity())) {
                        viewHolder.setVisible(R.id.tv_drug_status, true);
                        viewHolder.setText(R.id.tv_drug_status, "库存不足");
                    } else if (Integer.parseInt(item.getInventoryQuantity()) < 10) {
                        viewHolder.setVisible(R.id.tv_drug_status, true);
                        viewHolder.setText(R.id.tv_drug_status, "库存告急");
                    } else if (!item.isPublished()) {
                        viewHolder.setVisible(R.id.tv_drug_status, true);
                        viewHolder.setText(R.id.tv_drug_status, "已下架");
                    } else {
                        viewHolder.setVisible(R.id.tv_drug_status, false);
                        viewHolder.setText(R.id.tv_drug_status, "");
                    }
                }
            }


        } else {

            if (item.isSoldOut() || TextUtils.isEmpty(item.getInventoryQuantity())) {
                viewHolder.setVisible(R.id.tv_sold_out, true);

                viewHolder.setVisible(R.id.tv_drug_status, false);
                viewHolder.setText(R.id.tv_drug_status, "");
            } else {
                viewHolder.setVisible(R.id.tv_sold_out, false);

                if (Integer.parseInt(item.getAddedQuantity()) > Integer.parseInt(item.getInventoryQuantity())) {
                    viewHolder.setVisible(R.id.tv_drug_status, true);
                    viewHolder.setText(R.id.tv_drug_status, "库存不足");
                } else if (Integer.parseInt(item.getInventoryQuantity()) < 10) {
                    viewHolder.setVisible(R.id.tv_drug_status, true);
                    viewHolder.setText(R.id.tv_drug_status, "库存告急");

                } else if (!item.isPublished()) {
                    viewHolder.setVisible(R.id.tv_drug_status, true);
                    viewHolder.setText(R.id.tv_drug_status, "已下架");
                } else {
                    viewHolder.setVisible(R.id.tv_drug_status, false);
                    viewHolder.setText(R.id.tv_drug_status, "");
                }
            }


        }

        boolean isRx = false;
        if ("packet".equals(item.getCommodityType())) {
            List<DrugPackEntity> drugPackEntities = item.getDrugList();
            if (drugPackEntities != null && drugPackEntities.size() > 0) {
                for (DrugPackEntity entity : drugPackEntities) {
                    if (entity.isRx()) {
                        isRx = true;
                        break;
                    }
                }
            }
        } else {
            isRx = item.isRx();
        }
        viewHolder.setVisible(R.id.iv_rx, isRx);

        if ("drug".equals(item.getCommodityType())) {
            viewHolder.setText(R.id.item_name, item.getName());
            viewHolder.setText(R.id.item_spec, "规格：" + item.getSpec() + "x1");
            viewHolder.setVisible(R.id.item_spec, true);
            viewHolder.setVisible(R.id.item_articleQuantity, false);
            viewHolder.setVisible(R.id.spec_rv, false);
        } else if ("PT".equals(item.getCommodityType())) {
            viewHolder.setText(R.id.item_name, item.getName());
            viewHolder.setText(R.id.item_spec, !TextUtils.isEmpty(item.getSpec()) ? "规格：" + item.getSpec() + "x1" : "x1");
            viewHolder.setVisible(R.id.item_spec, true);
            viewHolder.setVisible(R.id.item_articleQuantity, false);
            viewHolder.setVisible(R.id.spec_rv, false);
        } else {
            viewHolder.setText(R.id.item_name, item.getName());
            viewHolder.setVisible(R.id.item_spec, false);
            viewHolder.setVisible(R.id.item_articleQuantity, true);
            String string = "";
            if (item.getInquiryQuantity() != null && item.getInquiryQuantity().length() > 0 && Integer.valueOf(item.getInquiryQuantity()) > 0) {
                string = string + "赠送：免费问诊 x" + item.getInquiryQuantity() + " ";
            }
            if (item.getArticleQuantity() != null && item.getArticleQuantity().length() > 0 && Integer.valueOf(item.getArticleQuantity()) > 0) {
                string = string + "赠送：患教文章 x" + item.getArticleQuantity() + " ";
            }
            if (!TextUtils.isEmpty(string)) {
                viewHolder.setVisible(R.id.item_articleQuantity, true);
                viewHolder.setText(R.id.item_articleQuantity, string);
            } else {
                viewHolder.setVisible(R.id.item_articleQuantity, false);

            }
//            specAdapter.setLabelList(item.getDrugList());
            RecyclerView drugRv = viewHolder.getView(R.id.spec_rv);
            specAdapter = new SpecAdapter(mContext, item.getDrugList());
            LinearLayoutManager manager = new LinearLayoutManager(mContext);
            manager.setInitialPrefetchItemCount(4);
            drugRv.setLayoutManager(manager);
            drugRv.setAdapter(specAdapter);

            specAdapter.setListener(new SpecAdapter.SpecListener() {
                @Override
                public void onClick(int index) {
                    MessageEvent messageEvent = new MessageEvent("childClick");
//                messageEvent.setAllChoice(!item.isChoice());
                    messageEvent.setChildPosition(viewHolder.getAdapterPosition());
                    messageEvent.setPosition(position);
                    EventBus.getDefault().post(messageEvent);
                }
            });
        }
        viewHolder.setText(R.id.item_price, "¥" + getPrice(item.getPrice()));


        viewHolder.setOnClickListener(R.id.ll_drug_content, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageEvent messageEvent = new MessageEvent("childClick");
//                messageEvent.setAllChoice(!item.isChoice());
                messageEvent.setChildPosition(viewHolder.getAdapterPosition());
                messageEvent.setPosition(position);
                EventBus.getDefault().post(messageEvent);
            }
        });

        TextView deleteTv = viewHolder.getView(R.id.tv_delete);
        deleteTv.setTag(viewHolder.getAdapterPosition());
        if (!deleteTv.hasOnClickListeners()) {
            deleteTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mDeleteClickListener != null) {
                        mDeleteClickListener.onDeleteClick(v, (Integer) v.getTag());
                    }
                }
            });
        }

        //list用来记录itemView是否滑开，避免recyclerview复用出现bug
        if (list.contains(viewHolder.getAdapterPosition() + "")) {
            viewHolder.itemView.scrollTo(deleteTv.getWidth(), 0);
        } else {
            viewHolder.itemView.scrollTo(0, 0);
        }
        //将item要展示的内容宽度设置为屏幕宽度，删除按钮则会隐藏在屏幕右侧
        RelativeLayout item_relative = viewHolder.getView(R.id.item_relative);
        ViewGroup.LayoutParams layoutParams = item_relative.getLayoutParams();
//        layoutParams.width = DruglistFragment.width - 100;
        layoutParams.width = DruglistFragment.width - UIUtils.dp2px(mContext, 39);
        HorizontalScrollView horizontalScrollView = viewHolder.getView(R.id.hsv);
        horizontalScrollView.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        //获取滑动的距离
                        int scrollX = horizontalScrollView.getScrollX();
                        //获取右侧删除按钮的宽度
                        int width = deleteTv.getWidth() + 20;
                        //如果滑动距离超过了删除按钮宽度的1/2，则将删除按钮滑出，否则隐藏
                        if (scrollX >= width / 2) {
                            viewHolder.itemView.scrollTo(width, 0);
                            //滑动的item记录下来
                            list.add(viewHolder.getAdapterPosition() + "");
                            if (DruglistFragment.viewEntity != null && DruglistFragment.viewEntity.getMoveView() != null && !DruglistFragment.viewEntity.getCommodityId().equals(item.getCommodityId() + position)) {
                                View view = DruglistFragment.viewEntity.getMoveView();
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        //延时执行 关闭其他的删除布局
                                        view.scrollTo(0, 0);
                                    }
                                }, 200);
                                //赋值上一个删除view
                                DruglistFragment.viewEntity.setCommodityId(item.getCommodityId() + position);
                                DruglistFragment.viewEntity.setMoveView(viewHolder.itemView);
                            }
                            //赋值上一个删除view
                            if (DruglistFragment.viewEntity == null || DruglistFragment.viewEntity.getMoveView() == null) {
                                DruglistFragment.viewEntity = new ViewEntity();
                                DruglistFragment.viewEntity.setMoveView(viewHolder.itemView);
                                DruglistFragment.viewEntity.setCommodityId(item.getCommodityId() + position);
                            }
                        } else {
                            viewHolder.itemView.scrollTo(0, 0);
                            if (list.contains(viewHolder.getAdapterPosition() + "")) {
                                //记录中移除
                                list.remove(viewHolder.getAdapterPosition() + "");
                            }
                            //把上一个删除view置空
                            if (DruglistFragment.viewEntity != null && DruglistFragment.viewEntity.getCommodityId() == item.getCommodityId()) {
                                DruglistFragment.viewEntity = null;
                            }
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:

                        break;
                }
                //注意此处返回false
                return false;
            }
        });
        //数量输入限制
        EditText itemNumEdt = viewHolder.getView(R.id.item_num_edt);
        itemNumEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String numStr = editable.toString().length() > 0 ? editable.toString() : "0";
                int num = Integer.parseInt(numStr);

                //控制加减号的图片
                if (num < 1) {
//                    viewHolder.setText(R.id.item_num_edt, "1");
//                    Toast.makeText(mContext, "左滑可删除该商品", Toast.LENGTH_SHORT).show();
                } else if (num == 1) {
                    viewHolder.setImageResource(R.id.num_add_iv, R.mipmap.plus2);
                    viewHolder.setImageResource(R.id.num_reduce_iv, R.mipmap.reduce1);
                } else if (num > Integer.parseInt(item.getInventoryQuantity())) {
                    viewHolder.setText(R.id.item_num_edt, item.getInventoryQuantity());
                } else if (num == Integer.parseInt(item.getInventoryQuantity())) {
                    viewHolder.setImageResource(R.id.num_add_iv, R.mipmap.plus1);
                    viewHolder.setImageResource(R.id.num_reduce_iv, R.mipmap.reduce2);
//                    Toast.makeText(mContext, "该商品当前最多可购买100件", Toast.LENGTH_SHORT).show();
                } else {
                    viewHolder.setImageResource(R.id.num_add_iv, R.mipmap.plus2);
                    viewHolder.setImageResource(R.id.num_reduce_iv, R.mipmap.reduce2);
                }
            }
        });

        viewHolder.setText(R.id.item_num_edt, item.getAddedQuantity());
        viewHolder.getView(R.id.item_num_edt).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    ALog.e("oakkk", "失去焦点： " + position + " ==> " + viewHolder.getAdapterPosition() + " ==> " + itemNumEdt.getText().toString());
                    if (item.getAddedQuantity().equals(itemNumEdt.getText().toString())) {
                        return;
                    }
                    ClickUtils.sendEvent(ClickApi.CartList.click_quantity_change, mContext, "药品数量改变");

                    String numStr = itemNumEdt.getText().toString();
                    if (TextUtils.isEmpty(numStr)){
                        itemNumEdt.setText("1");
                    }

                    MessageEvent messageEvent = new MessageEvent("childQuantityChange");
                    messageEvent.setQuantity(Integer.parseInt(itemNumEdt.getText().toString()));
                    messageEvent.setChildPosition(viewHolder.getAdapterPosition());
                    messageEvent.setPosition(position);
                    EventBus.getDefault().post(messageEvent);
                }
            }
        });
        //控制选中按钮
        if (item.isChecked()) {
            viewHolder.setBackgroundRes(R.id.choice_iv, R.mipmap.checked);
        } else {
            viewHolder.setBackgroundRes(R.id.choice_iv, R.mipmap.uncheck);
        }
        viewHolder.setOnClickListener(R.id.choice_iv, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MessageEvent messageEvent = new MessageEvent("childChoice");
                messageEvent.setAllChoice(!item.isChecked());
                messageEvent.setChildPosition(viewHolder.getAdapterPosition());
                messageEvent.setPosition(position);
                EventBus.getDefault().post(messageEvent);
            }
        });
        //点击减号
        viewHolder.setOnClickListener(R.id.num_reduce_iv, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addOrReduceNum(itemNumEdt, 0);
                ClickUtils.sendEvent(ClickApi.CartList.click_quantity_reduce, mContext, "药品数量改变-减");
                String numStr = itemNumEdt.getText().toString();
                if (TextUtils.isEmpty(numStr)){
                    itemNumEdt.setText("1");
                }
                MessageEvent messageEvent = new MessageEvent("childQuantityChange");
                messageEvent.setQuantity(Integer.parseInt(itemNumEdt.getText().toString()));
                messageEvent.setChildPosition(viewHolder.getAdapterPosition());
                messageEvent.setPosition(position);
                EventBus.getDefault().post(messageEvent);
            }
        });
        //点击加号
        viewHolder.setOnClickListener(R.id.num_add_iv, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addOrReduceNum(itemNumEdt, 1);
                ClickUtils.sendEvent(ClickApi.CartList.click_quantity_add, mContext, "药品数量改变-加");
                String numStr = itemNumEdt.getText().toString();
                if (TextUtils.isEmpty(numStr)){
                    itemNumEdt.setText("1");
                }
                MessageEvent messageEvent = new MessageEvent("childQuantityChange");
                messageEvent.setQuantity(Integer.parseInt(itemNumEdt.getText().toString()));
                messageEvent.setChildPosition(viewHolder.getAdapterPosition());
                messageEvent.setPosition(position);
                EventBus.getDefault().post(messageEvent);

            }
        });
    }


    /**
     * 控制数量的加减
     *
     * @param itemNumEdt 输入框控件
     * @param i          0代表-1  1代表+1
     */
    private void addOrReduceNum(EditText itemNumEdt, int i) {
        String numStr = itemNumEdt.getText().toString().length() > 0 ? itemNumEdt.getText().toString() : "";
        int num = Integer.parseInt(numStr);
        if (i == 0) {
            if (num <= 1) {
//                itemNumEdt.setText("");
            } else {
                num--;
            }
                itemNumEdt.setText(num + "");
        } else {
//            if (num >= 100) {
//            } else {
//                num++;
//            }
            num++;
            itemNumEdt.setText(num + "");
        }

    }

    private String getPrice(String price) {
        float f = Float.parseFloat(price);
        DecimalFormat decimalFormat = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String p = decimalFormat.format(f);//format 返回的是字符串
        if (p.substring(0, 1).equals(".")) {
            p = "0" + p;
        }
        return p;
    }

    public void setOnDeleteClickListener(OnDeleteClickLister listener) {
        this.mDeleteClickListener = listener;
    }

    public interface OnDeleteClickLister {
        void onDeleteClick(View view, int position);
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }
}
